﻿
using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Refit;
using StackExchange.Redis;
using WesRestApi;
using WesWebCore.Handlers;
namespace WesWebCore;

[AppStartup(700)]
public class Startup : AppStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddFileLogging("logs\\log.txt");

        services.Configure<RedisOption>(App.Configuration.GetSection("Redis"));

        var redisConnectionString = App.Configuration.GetValue<string>("Redis:ConnectionString");
        var config = ConfigurationOptions.Parse(redisConnectionString);
        config.AbortOnConnectFail = false;
        config.ConnectTimeout = 5000;  // 设置连接超时时间
        config.SyncTimeout = 5000;     // 设置同步操作超时时间
        config.KeepAlive = 180;       // 保持连接

        // 配置 Redis 单例
        services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(config));

        var serviceUrlsSection = App.Configuration.GetSection("ServiceUrls");
        services.Configure<RedisOption>(serviceUrlsSection);
        services
            .AddRefitClient<ICounterApi>()
            .ConfigureHttpClient(c => c.BaseAddress = new Uri(serviceUrlsSection.Get<string>("Job")));

        services.AddConsoleFormatter();
        //services.AddJwt<AuthHandler>();

        services.AddCorsAccessor();

        services.AddControllers()
                .AddInjectWithUnifyResult();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        // app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCorsAccessor();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseInject(string.Empty);

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}
